Page({
    data: {
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        tab: 'month',
        weeks: [],
        currentWeek: [],
        selectedDay: new Date().getDate(), // 默认选中今天
        checkInHistory: [], // 打卡历史记录
        canCheckIn: true, // 控制是否可以打卡
        currentDate: `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}-${String(new Date().getDate()).padStart(2, '0')}`
    },

    // 初始化时从本地读取历史记录
    onLoad: function () {
        // 从本地存储读取打卡记录
        //实现本地存储：
        const storedHistory = wx.getStorageSync('checkInHistory') || [];
        this.setData({ checkInHistory: storedHistory }, () => {
            this.generateCalendar(this.data.year, this.data.month);
            this.checkTodayCheckInStatus();
        });
    },

    generateCalendar(year, month) {
        const firstDayOfMonth = new Date(year, month - 1, 1);
        const lastDateOfMonth = new Date(year, month, 0).getDate();
        const dayOfWeek = firstDayOfMonth.getDay(); // 获取当月第一天是星期几

        let calendarData = [];
        let weekRow = [];

        // 填充空白单元格以对齐第一周的第一天
        for (let i = 0; i < dayOfWeek; i++) {
            weekRow.push({ day: '', selected: false, checkedIn: false });
        }

        for (let day = 1; day <= lastDateOfMonth; day++) {
            const isCheckedIn = this.data.checkInHistory.some(item => {
                const [y, m, d] = item.date.split('-');
                return parseInt(y) === year && parseInt(m) === month && parseInt(d) === day;
            });

            weekRow.push({
                day: day,
                selected: day === this.data.selectedDay,
                checkedIn: isCheckedIn
            });

            if ((day + dayOfWeek) % 7 === 0 || day === lastDateOfMonth) {
                calendarData.push(weekRow);
                weekRow = [];
            }
        }

        this.setData({ weeks: calendarData }, () => {
            this.updateCurrentWeek();
        });
    },

    updateCurrentWeek() {
        const { weeks, selectedDay } = this.data;
        let currentWeek = [];
        weeks.some((week) => {
            return week.some((day) => {
                if (day.day === selectedDay) {
                    currentWeek = week;
                    return true;
                }
            });
        });
        this.setData({ currentWeek });
    },

    prevMonth() {
        let { year, month } = this.data;
        if (month === 1) {
            year--;
            month = 12;
        } else {
            month--;
        }
        this.setData({ year, month }, () => {
            this.generateCalendar(year, month);
        });
    },

    nextMonth() {
        let { year, month } = this.data;
        if (month === 12) {
            year++;
            month = 1;
        } else {
            month++;
        }
        this.setData({ year, month }, () => {
            this.generateCalendar(year, month);
        });
    },

    toggleTab(e) {
        const tab = e.currentTarget.dataset.tab;
        this.setData({ tab }, () => {
            this.updateCurrentWeek();
        });
    },

    selectDay(e) {
        const day = parseInt(e.currentTarget.dataset.day);
        this.setData({ selectedDay: day }, () => {
            this.generateCalendar(this.data.year, this.data.month);
            this.checkTodayCheckInStatus();
        });
    },

    checkIn() {
        if (!this.isTodaySelected()) {
            wx.showToast({
                title: '只能打卡今天的日期',
                icon: 'none',
                duration: 2000
            });
            return;
        }

        if (!this.data.canCheckIn) {
            wx.showToast({
                title: '今日已打卡',
                icon: 'none',
                duration: 2000
            });
            return;
        }

        const today = new Date();
        const { year, month, selectedDay } = this.data;
        const date = `${year}-${String(month).padStart(2, '0')}-${String(selectedDay).padStart(2, '0')}`;
        const time = today.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

        const newHistory = [...this.data.checkInHistory, { date, time }];
        this.setData({
            checkInHistory: newHistory,
            canCheckIn: false
        }, () => {
            // 将最新记录持久化到本地存储
            wx.setStorageSync('checkInHistory', newHistory);
            wx.showToast({
                title: `今日已打卡！`,
                icon: 'success',
                duration: 2000
            });
        });
    },

    checkTodayCheckInStatus() {
        const todayStr = this.data.currentDate;
        const hasCheckedIn = this.data.checkInHistory.some(item => item.date === todayStr);
        this.setData({ canCheckIn: !hasCheckedIn });
    },

    isTodaySelected() {
        const today = new Date();
        return this.data.selectedDay === today.getDate() &&
               this.data.month === today.getMonth() + 1 &&
               this.data.year === today.getFullYear();
    }
});